
window.App = {
		
	get : function(url) {
		var data = "<h1> failed to load url : " + url + "</h1>";
		$.ajax({
			async: false,
			url: url,
			success: function(response) {
				data = response;
			}
		});
		return data;
	}

}


App.Company = Backbone.Model.extend({
	urlRoot : "api/company",
	/*
	defaults : {
		id: null,
		name: "please insert company name",
		address: "please insert company address",
		password: "please insert user password",
	}
	*/
});


App.CompanyCollection = Backbone.Collection.extend({
	url : "api/company",
	model : App.Company
});


App.User = Backbone.Model.extend({
	urlRoot : "api/user",
	/*
	defaults : {
		id: null,
		name: "please insert user name",
		email: "please insert user email",
		password: "please insert user password",
	}
	 */
});


App.UserCollection = Backbone.Collection.extend({
    url : "api/user",
	model : App.User
});


App.ChromeView = Backbone.View.extend({
	initialize: function () {},
	template: _.template( App.get("tpl/chrome.html") ),
	render: function () {
		var view = this;
		$.ajax({
			"type":"POST",
			"url" : "api/login"
		}).error(function(response){
			App.user = null;
			$(view.el).html(view.template());
			Backbone.history.loadUrl( Backbone.history.fragment , { trigger: true } );
		}).done(function(response){
			App.user = response;
			$(view.el).html(view.template());
			Backbone.history.loadUrl( Backbone.history.fragment , { trigger: true } );
		});
		return this;
	},
    doLogin : function() {
		var view = this;
		$.ajax({
			"type":"POST",
			"url" : "api/login",
			"data":{
				"email"		:	$("#email").val(),
				"password"	:	$("#password").val()
			}
		}).error(function(response){
			App.user = null;
			$(view.el).html(view.template());
			Backbone.history.loadUrl( Backbone.history.fragment , { trigger: true } );
		}).done(function(response){
			App.user = response;
			$(view.el).html(view.template());
			Backbone.history.loadUrl( Backbone.history.fragment , { trigger: true } );
		});
    },
    doLogout : function() {
		var view = this;
		$.ajax({
			"type":"POST",
			"url" : "api/logout"
		}).always(function(response){
			App.user = response;
			$(view.el).html(view.template());
			App.router.navigate( "" , { trigger: true } );
		});
    },
    updateMenu: function () {
		var fragment = Backbone.history.fragment == "" ? "home" : Backbone.history.fragment;
		$("li", this.el).each(function(){
			$(this).hasClass(fragment) ? $(this).addClass("active") : $(this).removeClass("active");
		});
	},
    events: {
		"click button.login" : "doLogin",
		"click li.logout a" : "doLogout"
    },
});


App.HomeView = Backbone.View.extend({
	template: _.template( App.get("tpl/home.html") ),
	render: function () {
		$(this.el).html(this.template());
		return this;
	},
});


App.AgendaView = Backbone.View.extend({
	template: _.template( App.get("tpl/agenda.html") ),
	render: function () {
		$(this.el).html(this.template());
		return this;
	},
});


App.HealthView = Backbone.View.extend({
	template: _.template( App.get("tpl/health.html") ),
	render: function () {
		$(this.el).html(this.template());
		return this;
	},
});


App.BillingView = Backbone.View.extend({
	template: _.template( App.get("tpl/billing.html") ),
	render: function () {
		$(this.el).html(this.template());
		return this;
	},
});


App.ShoppingView = Backbone.View.extend({
	template: _.template( App.get("tpl/shopping.html") ),
	render: function () {
		$(this.el).html(this.template());
		return this;
	},
});


App.UserListView = Backbone.View.extend({
	template: _.template( App.get("tpl/userList.html") ),
	initialize: function () {
		_.bindAll(this, 'render', 'appendItem');
	},
	render: function () {
		$(this.el).html(this.template());
        _.each(this.collection.models, this.appendItem, this);
		return this;
	},
    appendItem: function (user) {
    	var userListItemView = new App.UserListItemView({
    		userListView : $(this.el),
    		model : user,
		});
    	userListItemView.userListView = this;
    	$(".users tbody", this.el).append( userListItemView.render().el );
    },
	events: {
		'click button.create': 'create',
	},
	create: function() {
		var view = this;
		var user = new App.User( { companyId : App.user.companyId } );
		this.collection.create(user, {
			success: function() {
				view.undelegateEvents();
				var userEditView = new App.UserEditView({
					model: user,
					el : $(view.el)
				});
				userEditView.render();
			}
		});
	},
});


App.UserListItemView = Backbone.View.extend({
	tagName:"tr",
	template: _.template( App.get("tpl/userListItem.html") ),
	initialize: function () {
		_.bindAll(this, 'render', 'unrender', 'remove');
		this.model.bind('remove', this.unrender);
	},
	render:function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	unrender: function(){
		$(this.el).remove();
	},
	events: {
		'click a.delete': 'remove',
		'click a.edit': 'edit',
	},
	remove: function(e) {
		if(
			!$(e.currentTarget).hasClass("disabled") 
			&& 
			confirm("Deseja eliminar este cliente ?") 
		) {
			this.model.destroy();
		};
	},
	edit: function(){
		this.userListView.undelegateEvents();
		var userEditView = new App.UserEditView({
			model: this.model,
			el : $(this.userListView.el)
		});
		userEditView.render();
	},
});

App.UserEditView = Backbone.View.extend({
	
	template: _.template( App.get("tpl/userEdit.html") ),
	
	events: {
		'click button.save': 'save',
		'click button.cancel': 'cancel',
		'change input' : 'onChange',
	},
	
	render: function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	
	onChange: function(){
		this.model.set({ name : this.$('input.name').val() });
		this.model.set({ email : this.$('input.email').val() });
		this.model.set({ password : this.$('input.password').val() });
	},
	
	save: function () {
		var self = this;
		this.model.save({}, {
			success : function(model, response){
		    	var userCollection = new App.UserCollection();
		    	userCollection.fetch({
					data : {
			    		companyId : App.user.companyId // self.model.get('companyId')
					},
					success : function( users ) {
						self.undelegateEvents();
						var userListView = new App.UserListView({el : self.el, collection : users });
						userListView.render();
					}
				});
				
			}
		});
	},
	
	cancel: function () {
		var self = this;
    	var userCollection = new App.UserCollection();
    	userCollection.fetch({
			data : {
	    		companyId : App.user.companyId // this.model.get('companyId')
			},
			success : function( users ) {
				self.undelegateEvents();
				var userListView = new App.UserListView({el : self.el, collection : users });
				userListView.render();
			}
		});
	},
	
});

App.CompanyEditView = Backbone.View.extend({
	
	template: _.template( App.get("tpl/companyEdit.html") ),
	
	events: {
		'click button.save': 'save',
		'click button.cancel': 'cancel',
		'change input' : 'onChange',
	},
	
	render: function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	
	onChange: function(){
		this.model.set({ name : this.$('input.name').val() });
	},
	
	save: function () {
		var self = this;
		this.model.save({}, {
			success : function(model, response){
			}
		});
	},
	
	cancel: function () {
	},
	
});


App.UserView = Backbone.View.extend({
	template: _.template( App.get("tpl/user.html") ),
	render: function () {
		if(App.user)
		{
			$(this.el).html(this.template());
			this.renderUserList();
			this.renderCompanyEdit();
		}
		return this;
	},
	renderCompanyEdit : function() {
		var company = new App.Company({ id : App.user.companyId });
		var view = this;
		company.fetch({
			data : {},
			success : function( company ) {
				var companyEditView = new App.CompanyEditView({el : $('.companyEdit', view.el), model : company });
				companyEditView.render();
			}
		});
	},
	renderUserList : function() {
		var userCollection = new App.UserCollection();
		var view = this;
		userCollection.fetch({
			data : {
				companyId : App.user.companyId
			},
			success : function( users ) {
				var userListView = new App.UserListView({el : $('.userList', view.el), collection : userCollection });
				userListView.render();
			}
		});
	},
});


App.Router = Backbone.Router.extend({
	
	routes : {
		""			: "home",
		"home"		: "home",
		"agenda"	: "agenda",
		"health"	: "health",
		"billing"	: "billing",
		"shopping"	: "shopping",
		"user"		: "user",
		"logout"	: "logout",
	},

	initialize: function () {
		this.on('all', this.routeChangeHandler, this)
		App.chromeView = new App.ChromeView({ el : document.body });
		App.chromeView.render();
	},
	
	routeChangeHandler: function(route) {
		App.chromeView.updateMenu();
	},

	home: function () {
		App.homeView = new App.HomeView({el : $('#chromeViewContent') });
		App.homeView.render();
	},
	
	agenda: function () {
		App.agendaView = new App.AgendaView({el : $('#chromeViewContent') });
		App.agendaView.render();
	},
	
	health: function () {
		App.healthView = new App.HealthView({el : $('#chromeViewContent') });
		App.healthView.render();
	},
	
	billing: function () {
		App.billingView = new App.BillingView({el : $('#chromeViewContent') });
		App.billingView.render();
	},
	
	shopping: function () {
		App.shoppingView = new App.ShoppingView({el : $('#chromeViewContent') });
		App.shoppingView.render();
	},
	
	user: function () {
		App.userView = new App.UserView({el : $('#chromeViewContent') });
		App.userView.render();
	},
	
	logout: function () {
	},
	
});


$(function() {
	App.router = new App.Router;
	Backbone.history.start();
});
